@{
    ViewData["Title"] = "修改计划";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<!-- 直接在Edit页面引入必要的CSS和JS，确保iframe中正确加载 -->
<link rel="stylesheet" href="~/libs/scripts/layui-v2.5.6/layui/css/layui.css" />

<style>
.edit-dialog {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    background: rgba(0,0,0,0.6);
    z-index: 9999;
    display: flex;
    align-items: center;
    justify-content: center;
    backdrop-filter: blur(2px);
}

.edit-content {
    width: 90%;
    max-width: 1000px;
    max-height: 90vh;
    background: white;
    border-radius: 12px;
    display: flex;
    flex-direction: column;
    box-shadow: 0 8px 32px rgba(0,0,0,0.2);
    overflow: hidden;
}

.edit-header {
    padding: 20px 24px;
    border-bottom: 1px solid #e8e8e8;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
}

.edit-header h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
}

.edit-body {
    flex: 1;
    padding: 24px;
    overflow-y: auto;
    background: #fafbfc;
}

.edit-footer {
    padding: 16px 24px;
    border-top: 1px solid #e8e8e8;
    text-align: right;
    background: white;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}

.form-section {
    background: white;
    border-radius: 8px;
    padding: 24px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.section-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin-bottom: 20px;
    padding-bottom: 8px;
    border-bottom: 2px solid #667eea;
    position: relative;
}

.section-title::after {
    content: '';
    position: absolute;
    bottom: -2px;
    left: 0;
    width: 30px;
    height: 2px;
    background: #667eea;
}

.form-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
}

.form-item {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.form-label {
    font-size: 14px;
    font-weight: 500;
    color: #333;
    display: flex;
    align-items: center;
    gap: 4px;
}

.form-input {
    position: relative;
}

.form-input .layui-input,
.form-input .layui-select,
.form-input .layui-textarea {
    border: 1px solid #d9d9d9;
    border-radius: 6px;
    padding: 10px 12px;
    font-size: 14px;
    transition: all 0.3s ease;
    background: white;
}

.form-input .layui-input:focus,
.form-input .layui-select:focus,
.form-input .layui-textarea:focus {
    border-color: #667eea;
    box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
    outline: none;
}

.frequency-input {
    display: flex;
    align-items: center;
    gap: 8px;
}

.frequency-number {
    flex: 1;
    min-width: 80px;
}

.frequency-unit {
    flex: 1;
    min-width: 100px;
}

.auto-generate-wrapper {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 0;
}

.auto-generate-wrapper .layui-form-checkbox {
    margin: 0;
}

.auto-generate-hint {
    font-size: 12px;
    color: #999;
    font-style: italic;
}

.tab-container {
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.tab-header {
    display: flex;
    background: #f5f5f5;
    border-bottom: 1px solid #e8e8e8;
}

.tab-item {
    flex: 1;
    padding: 16px 24px;
    cursor: pointer;
    text-align: center;
    border-bottom: 3px solid transparent;
    color: #666;
    font-weight: 500;
    transition: all 0.3s ease;
    position: relative;
}

.tab-item:hover {
    background: #eef2ff;
    color: #667eea;
}

.tab-item.active {
    color: #667eea;
    background: white;
    border-bottom-color: #667eea;
}

.tab-content {
    padding: 24px;
    min-height: 200px;
}

.tab-pane {
    display: none;
}

.tab-pane.active {
    display: block;
}

.table-toolbar {
    margin-bottom: 16px;
    display: flex;
    gap: 8px;
}

.data-table {
    width: 100%;
    border-collapse: collapse;
    border: 1px solid #e8e8e8;
    border-radius: 6px;
    overflow: hidden;
    background: white;
}

.data-table th,
.data-table td {
    padding: 12px 16px;
    border-bottom: 1px solid #f0f0f0;
    text-align: left;
    font-size: 14px;
}

.data-table th {
    background: #fafbfc;
    font-weight: 600;
    color: #333;
    border-bottom: 2px solid #e8e8e8;
}

.data-table tbody tr:hover {
    background: #f8f9ff;
}

.empty-data {
    text-align: center;
    color: #999;
    padding: 40px;
    font-style: italic;
    background: #fafbfc;
}

.close-btn {
    background: rgba(255,255,255,0.2);
    border: none;
    font-size: 20px;
    cursor: pointer;
    color: white;
    padding: 8px;
    border-radius: 6px;
    transition: all 0.3s ease;
    width: 36px;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.close-btn:hover {
    background: rgba(255,255,255,0.3);
    transform: rotate(90deg);
}

.required {
    color: #ff4d4f;
    margin-right: 2px;
}

.layui-form-item {
    margin-bottom: 0;
}

.full-width-item {
    grid-column: 1 / -1;
}

.btn-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    color: white;
    padding: 10px 20px;
    border-radius: 6px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
}

.btn-primary:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.btn-success {
    background: linear-gradient(135deg, #36d1dc 0%, #5b86e5 100%);
    border: none;
    color: white;
    padding: 10px 20px;
    border-radius: 6px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
}

.btn-success:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(54, 209, 220, 0.4);
}

.btn-secondary {
    background: #f5f5f5;
    border: 1px solid #d9d9d9;
    color: #666;
    padding: 10px 20px;
    border-radius: 6px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
}

.btn-secondary:hover {
    background: #e8e8e8;
    border-color: #bfbfbf;
}

.loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255,255,255,0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
}

.loading-spinner {
    width: 40px;
    height: 40px;
    border: 3px solid #f3f3f3;
    border-top: 3px solid #667eea;
    border-radius: 50%;
}

/* 响应式设计 */
</style>

<div class="edit-dialog" id="editDialog">
    <div class="edit-content">
        <div class="edit-header">
            <h3>修改计划</h3>
            <button class="close-btn" onclick="closeDialog()" title="关闭">&times;</button>
        </div>
        
        <div class="edit-body">
            <form class="layui-form" id="editForm" lay-filter="editForm">
                <input type="hidden" id="Id" name="Id" value="@ViewBag.Id" />
                
                <!-- 基本信息 -->
                <div class="form-section">
                    <div class="section-title">基本信息</div>
                    <div class="form-grid">
                        <div class="form-item">
                            <label class="form-label">
                                <span class="required">*</span>计划编码
                            </label>
                            <div class="form-input">
                                <input type="text" id="ProjectCode" name="ProjectCode" required lay-verify="required" placeholder="请输入计划编码，如：PLAN20250001" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        
                        <div class="form-item">
                            <label class="form-label">自动生成</label>
                            <div class="form-input auto-generate-wrapper">
                                <input type="checkbox" id="AutoGenerate" name="AutoGenerate" lay-filter="autoGenerate" title="自动生成" />
                                <span class="auto-generate-hint">勾选后自动生成编码</span>
                            </div>
                        </div>
                        
                        <div class="form-item">
                            <label class="form-label">
                                <span class="required">*</span>计划名称
                            </label>
                            <div class="form-input">
                                <input type="text" id="ProjectName" name="ProjectName" required lay-verify="required" placeholder="请输入计划名称" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        
                        <div class="form-item">
                            <label class="form-label">
                                <span class="required">*</span>计划类型
                            </label>
                            <div class="form-input">
                                <select id="ProjectType" name="ProjectType" lay-verify="required">
                                    <option value="">请选择计划类型</option>
                                    <option value="设备点检计划">设备点检计划</option>
                                    <option value="设备保养计划">设备保养计划</option>
                                    <option value="综合维护计划">综合维护计划</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="form-item">
                            <label class="form-label">执行频率</label>
                            <div class="form-input frequency-input">
                                <input type="number" id="FrequencyValue" name="FrequencyValue" value="1" class="layui-input frequency-number" min="1" placeholder="频率">
                                <select id="FrequencyUnit" name="FrequencyUnit" class="frequency-unit">
                                    <option value="小时">小时</option>
                                    <option value="天" selected>天</option>
                                    <option value="周">周</option>
                                    <option value="月">月</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="form-item">
                            <label class="form-label">开始日期</label>
                            <div class="form-input">
                                <input type="text" id="StartDate" name="StartDate" placeholder="请选择开始日期" class="layui-input" lay-key="1" readonly>
                            </div>
                        </div>
                        
                        <div class="form-item">
                            <label class="form-label">结束日期</label>
                            <div class="form-input">
                                <input type="text" id="EndDate" name="EndDate" placeholder="请选择结束日期" class="layui-input" lay-key="2" readonly>
                            </div>
                        </div>
                        
                        <div class="form-item">
                            <label class="form-label">状态</label>
                            <div class="form-input">
                                <select id="WhethertoEnable" name="WhethertoEnable">
                                    <option value="">请选择状态</option>
                                    <option value="启用">启用</option>
                                    <option value="停用">停用</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 项目内容 -->
                    <div class="form-item full-width-item">
                        <label class="form-label">项目内容</label>
                        <div class="form-input">
                            <textarea id="ProjectContent" name="ProjectContent" placeholder="请输入项目的详细内容..." class="layui-textarea" style="min-height: 80px; resize: vertical;"></textarea>
                        </div>
                    </div>
                    
                    <!-- 标准和备注 -->
                    <div class="form-item full-width-item">
                        <label class="form-label">标准要求</label>
                        <div class="form-input">
                            <textarea id="Standard" name="Standard" placeholder="请输入计划的标准要求和规范..." class="layui-textarea" style="min-height: 80px; resize: vertical;"></textarea>
                        </div>
                    </div>
                </div>
                
                <!-- 标签页 -->
                <div class="tab-container">
                    <div class="tab-header">
                        <div class="tab-item active" data-tab="equipment">
                            <i class="layui-icon layui-icon-engine" style="margin-right: 4px;"></i>
                            设备清单
                        </div>
                        <div class="tab-item" data-tab="inspection">
                            <i class="layui-icon layui-icon-survey" style="margin-right: 4px;"></i>
                            点检项目
                        </div>
                    </div>
                    
                    <div class="tab-content">
                        <!-- 设备清单标签页 -->
                        <div class="tab-pane active" id="equipment-tab">
                            <div class="table-toolbar">
                                <button type="button" class="layui-btn layui-btn-sm" onclick="addEquipment()">
                                    <i class="layui-icon layui-icon-add-1"></i> 新增设备
                                </button>
                                <button type="button" class="layui-btn layui-btn-sm layui-btn-danger" onclick="deleteEquipment()">
                                    <i class="layui-icon layui-icon-delete"></i> 删除选中
                                </button>
                                <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" onclick="importEquipment()">
                                    <i class="layui-icon layui-icon-upload"></i> 批量导入
                                </button>
                            </div>
                            <table class="data-table" id="equipmentTable">
                                <thead>
                                    <tr>
                                        <th width="50">
                                            <input type="checkbox" lay-filter="equipmentCheckAll" lay-skin="primary">
                                        </th>
                                        <th>设备编码</th>
                                        <th>设备名称</th>
                                        <th>设备品牌</th>
                                        <th>规格型号</th>
                                        <th>所属车间</th>
                                        <th>备注</th>
                                        <th width="120">操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td colspan="8" class="empty-data">
                                            <i class="layui-icon layui-icon-face-cry" style="font-size: 24px; color: #ccc; margin-bottom: 8px; display: block;"></i>
                                            暂无设备数据，请点击"新增设备"添加
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        
                        <!-- 点检项目标签页 -->
                        <div class="tab-pane" id="inspection-tab">
                            <div class="table-toolbar">
                                <button type="button" class="layui-btn layui-btn-sm" onclick="addInspection()">
                                    <i class="layui-icon layui-icon-add-1"></i> 新增项目
                                </button>
                                <button type="button" class="layui-btn layui-btn-sm layui-btn-danger" onclick="deleteInspection()">
                                    <i class="layui-icon layui-icon-delete"></i> 删除选中
                                </button>
                                <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" onclick="copyFromTemplate()">
                                    <i class="layui-icon layui-icon-template-1"></i> 从模板复制
                                </button>
                            </div>
                            <table class="data-table" id="inspectionTable">
                                <thead>
                                    <tr>
                                        <th width="50">
                                            <input type="checkbox" lay-filter="inspectionCheckAll" lay-skin="primary">
                                        </th>
                                        <th>项目编码</th>
                                        <th>项目名称</th>
                                        <th>检查点</th>
                                        <th>检查标准</th>
                                        <th>检查方法</th>
                                        <th>备注</th>
                                        <th width="120">操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td colspan="8" class="empty-data">
                                            <i class="layui-icon layui-icon-face-cry" style="font-size: 24px; color: #ccc; margin-bottom: 8px; display: block;"></i>
                                            暂无点检项目，请点击"新增项目"添加
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </form>
        </div>
        
        <div class="edit-footer">
            <button class="btn-primary" onclick="saveData()">
                <i class="layui-icon layui-icon-ok"></i> 保存
            </button>
            <button class="btn-success" onclick="enablePlan()">
                <i class="layui-icon layui-icon-play"></i> 启用
            </button>
            <button class="btn-secondary" onclick="closeDialog()">
                <i class="layui-icon layui-icon-close"></i> 取消
            </button>
        </div>
    </div>
</div>

<!-- 确保jQuery和layui正确加载 -->
<script src="~/libs/jquery/jquery.js"></script>
<script src="~/libs/scripts/layui-v2.5.6/layui/layui.js"></script>

<script>
// 添加调试信息
console.log('jQuery加载状态:', typeof $ !== 'undefined' ? '已加载' : '未加载');
console.log('layui加载状态:', typeof layui !== 'undefined' ? '已加载' : '未加载');

// 全局变量声明
var layuiForm, layuiLayer, layuiLaydate;

// 等待layui加载完成
function initializeLayui() {
    if (typeof layui === 'undefined') {
        console.log('layui未加载，1秒后重试...');
        setTimeout(initializeLayui, 1000);
        return;
    }
    
    console.log('layui已加载，开始初始化...');
    
    layui.use(['form', 'layer', 'laydate'], function(){
        // 保存layui组件到全局变量
        layuiForm = layui.form;
        layuiLayer = layui.layer;
        layuiLaydate = layui.laydate;
        
        var form = layuiForm;
        var layer = layuiLayer;
        var laydate = layuiLaydate;
        
        console.log('layui组件初始化成功');
        
        // 初始化日期选择器
        laydate.render({
            elem: '#StartDate',
            type: 'date',
            format: 'yyyy-MM-dd',
            theme: '#667eea'
        });
        
        laydate.render({
            elem: '#EndDate',
            type: 'date',
            format: 'yyyy-MM-dd',
            theme: '#667eea'
        });
        
        // 标签页切换
        $('.tab-item').click(function() {
            var tabId = $(this).data('tab');
            $('.tab-item').removeClass('active');
            $('.tab-pane').removeClass('active');
            $(this).addClass('active');
            $('#' + tabId + '-tab').addClass('active');
        });
        
        // 自动生成编码
        form.on('checkbox(autoGenerate)', function(data){
            if(data.elem.checked){
                generateCode();
            }
        });
        
        // 如果是编辑模式，加载数据
        var id = $('#Id').val();
        if (id && id > 0) {
            loadData(id);
        }
        
        // 生成编码
        function generateCode() {
            var now = new Date();
            var year = now.getFullYear();
            var month = String(now.getMonth() + 1).padStart(2, '0');
            var day = String(now.getDate()).padStart(2, '0');
            var hour = String(now.getHours()).padStart(2, '0');
            var minute = String(now.getMinutes()).padStart(2, '0');
            var code = 'PLAN' + year + month + day + hour + minute;
            $('#ProjectCode').val(code);
            
            // 简单的背景色变化效果
            $('#ProjectCode').css('background-color', '#e6f7ff');
            setTimeout(function() {
                $('#ProjectCode').css('background-color', 'white');
            }, 1000);
        }
        
        // 将生成编码函数暴露到全局
        window.generateCode = generateCode;
        
        // 加载数据
        function loadData(id) {
            // 显示简单的加载状态
            var loadingHtml = '<div class="loading-overlay"><div class="loading-spinner" style="border: 3px solid #f3f3f3; border-top: 3px solid #667eea; border-radius: 50%; width: 40px; height: 40px;"></div></div>';
            $('.edit-body').append(loadingHtml);
            
            // 添加旋转动画
            var spinner = $('.loading-spinner');
            var rotation = 0;
            var rotateInterval = setInterval(function() {
                rotation += 10;
                spinner.css('transform', 'rotate(' + rotation + 'deg)');
            }, 50);
            
            $.ajax({
                url: '/ProductionSystem/Maintenanceplan/Get/' + id,
                type: 'GET',
                success: function(result) {
                    clearInterval(rotateInterval);
                    $('.loading-overlay').remove();
                    
                    if (result.success && result.data) {
                        var data = result.data;
                        
                        // 填充基本信息
                        $('#ProjectCode').val(data.projectCode || '');
                        $('#ProjectName').val(data.projectName || '');
                        $('#ProjectType').val(data.projectType || '');
                        $('#WhethertoEnable').val(data.whethertoEnable || '');
                        $('#ProjectContent').val(data.projectContent || '');
                        $('#Standard').val(data.standard || '');
                        
                        // 重新渲染表单
                        form.render();
                        
                        layer.msg('数据加载成功', {icon: 1, time: 1500});
                    } else {
                        layer.msg('加载数据失败：' + (result.message || '未知错误'), {icon: 2});
                    }
                },
                error: function(xhr, status, error) {
                    clearInterval(rotateInterval);
                    $('.loading-overlay').remove();
                    layer.msg('网络错误：' + error, {icon: 2});
                    console.error('加载数据失败:', error, xhr.responseText);
                }
            });
        }
        
        // 将loadData函数暴露到全局
        window.loadData = loadData;
    });
}

// 启动初始化
initializeLayui();

// 保存数据
function saveData() {
    // 检查layui是否已加载
    if (!layuiLayer) {
        console.error('layui未正确加载');
        alert('页面组件未完全加载，请刷新页面重试');
        return;
    }
    
    var layer = layuiLayer;
    
    // 获取表单数据
    var formData = {
        Id: parseInt($('#Id').val()) || 0,
        ProjectCode: $('#ProjectCode').val().trim(),
        ProjectName: $('#ProjectName').val().trim(),
        ProjectType: $('#ProjectType').val(),
        ProjectContent: $('#ProjectContent').val().trim(),
        WhethertoEnable: $('#WhethertoEnable').val(),
        Standard: $('#Standard').val().trim()
    };
    
    // 添加调试信息
    console.log('状态字段原始值:', $('#WhethertoEnable').val());
    console.log('状态字段选中的文本:', $('#WhethertoEnable option:selected').text());
    console.log('完整表单数据:', formData);
    
    // 验证必填项
    if (!formData.ProjectCode) {
        layer.msg('请输入计划编码', {icon: 2});
        $('#ProjectCode').focus();
        return;
    }
    if (!formData.ProjectName) {
        layer.msg('请输入计划名称', {icon: 2});
        $('#ProjectName').focus();
        return;
    }
    if (!formData.ProjectType) {
        layer.msg('请选择计划类型', {icon: 2});
        return;
    }
    
    // 显示加载层
    var loadIndex = layer.load(2, {shade: [0.3, '#000']});
    
    // 确定API URL
    var url = formData.Id > 0 ? 
        '/ProductionSystem/Maintenanceplan/UpdateMaintenanceplan' : 
        '/ProductionSystem/Maintenanceplan/AddMaintenanceplan';
    
    console.log('提交数据:', formData);
    console.log('API URL:', url);
    
    $.ajax({
        url: url,
        type: 'POST',
        data: formData,
        success: function(result) {
            layer.close(loadIndex);
            console.log('保存结果:', result);
            
            if (result.success) {
                var isAdd = formData.Id <= 0;
                var message = isAdd ? '添加成功' : '更新成功';
                
                layer.msg(message, {icon: 1, time: 1500}, function(){
                    // 保存成功后关闭页面并刷新父页面
                    closeDialogWithRefresh();
                });
            } else {
                layer.msg(result.message || '保存失败', {icon: 2});
            }
        },
        error: function(xhr, status, error) {
            layer.close(loadIndex);
            console.error('保存失败:', error, xhr.responseText);
            layer.msg('网络错误：' + error, {icon: 2});
        }
    });
}

// 启用计划
function enablePlan() {
    // 检查layui是否已加载
    if (!layuiLayer || !layuiForm) {
        console.error('layui未正确加载');
        alert('页面组件未完全加载，请刷新页面重试');
        return;
    }
    
    var layer = layuiLayer;
    var form = layuiForm;
    
    var id = $('#Id').val();
    if (!id || id <= 0) {
        layer.msg('请先保存计划再启用', {icon: 2});
        return;
    }
    
    layer.confirm('确定要启用此计划吗？启用后计划将开始执行。', {
        icon: 3, 
        title:'确认启用',
        btn: ['确定启用', '取消']
    }, function(index){
        $('#WhethertoEnable').val('是');
        form.render('select');
        layer.close(index);
        layer.msg('已设置为启用状态，请点击保存', {icon: 1, time: 2000});
    });
}

// 关闭对话框
function closeDialog() {
    if (parent && parent.layer) {
        // 如果是在父窗口的layer中打开的，关闭layer
        var index = parent.layer.getFrameIndex(window.name);
        parent.layer.close(index);
    } else {
        // 否则跳转回列表页
        window.location.href = '/ProductionSystem/Maintenanceplan/Index';
    }
}

// 关闭对话框并刷新父页面
function closeDialogWithRefresh() {
    if (parent && parent.layer) {
        // 如果是在父窗口的layer中打开的
        var index = parent.layer.getFrameIndex(window.name);
        
        // 尝试刷新父页面的表格数据
        try {
            // 方法1: 如果父页面有刷新表格的方法
            if (parent.refreshTable && typeof parent.refreshTable === 'function') {
                parent.refreshTable();
            }
            // 方法2: 如果父页面使用layui table
            else if (parent.layui && parent.layui.table) {
                parent.layui.table.reload('maintenanceplanTable');
            }
            // 方法3: 如果父页面有全局刷新方法
            else if (parent.loadTableData && typeof parent.loadTableData === 'function') {
                parent.loadTableData();
            }
            // 方法4: 如果父页面有搜索方法
            else if (parent.searchData && typeof parent.searchData === 'function') {
                parent.searchData();
            }
            // 方法5: 直接刷新父页面
            else {
                parent.location.reload();
            }
        } catch (e) {
            console.log('刷新父页面失败，尝试直接刷新:', e);
            // 如果上述方法都失败，直接刷新父页面
            parent.location.reload();
        }
        
        // 关闭当前弹窗
        parent.layer.close(index);
    } else {
        // 如果不是在弹窗中，直接跳转回列表页
        window.location.href = '/ProductionSystem/Maintenanceplan/Index';
    }
}

// 设备清单相关函数
function addEquipment() {
    if (!layuiLayer) {
        alert('页面组件未完全加载，请刷新页面重试');
        return;
    }
    layuiLayer.open({
        type: 1,
        title: '新增设备',
        area: ['600px', '400px'],
        content: '<div style="padding: 20px;">设备选择功能开发中...</div>'
    });
}

function deleteEquipment() {
    if (!layuiLayer) {
        alert('页面组件未完全加载，请刷新页面重试');
        return;
    }
    layuiLayer.confirm('确定要删除选中的设备吗？', {icon: 3, title:'提示'}, function(index){
        layuiLayer.msg('删除功能开发中', {icon: 1});
        layuiLayer.close(index);
    });
}

function importEquipment() {
    if (!layuiLayer) {
        alert('页面组件未完全加载，请刷新页面重试');
        return;
    }
    layuiLayer.msg('批量导入功能开发中', {icon: 1});
}

// 点检项目相关函数
function addInspection() {
    if (!layuiLayer) {
        alert('页面组件未完全加载，请刷新页面重试');
        return;
    }
    layuiLayer.open({
        type: 1,
        title: '新增点检项目',
        area: ['700px', '500px'],
        content: '<div style="padding: 20px;">点检项目配置功能开发中...</div>'
    });
}

function deleteInspection() {
    if (!layuiLayer) {
        alert('页面组件未完全加载，请刷新页面重试');
        return;
    }
    layuiLayer.confirm('确定要删除选中的点检项目吗？', {icon: 3, title:'提示'}, function(index){
        layuiLayer.msg('删除功能开发中', {icon: 1});
        layuiLayer.close(index);
    });
}

function copyFromTemplate() {
    if (!layuiLayer) {
        alert('页面组件未完全加载，请刷新页面重试');
        return;
    }
    layuiLayer.msg('模板复制功能开发中', {icon: 1});
}

// 页面加载完成后的初始化
$(document).ready(function() {
    console.log('页面加载完成，ID:', $('#Id').val());
    
    // 添加键盘快捷键
    $(document).keydown(function(e) {
        if (e.ctrlKey && e.keyCode === 83) { // Ctrl+S
            e.preventDefault();
            saveData();
        }
        if (e.keyCode === 27) { // ESC
            closeDialog();
        }
    });
    
    // 自动保存功能（可选）
    var autoSaveTimer;
    $('input, textarea, select').on('input change', function() {
        clearTimeout(autoSaveTimer);
        autoSaveTimer = setTimeout(function() {
            // 这里可以实现自动保存草稿功能
            console.log('表单数据已更改');
        }, 5000);
    });
});
</script> 